package com.xc.quickstart.common.util;

import cn.hutool.core.codec.Base64;
import com.xc.quickstart.common.model.JwtParseModel;
import io.jsonwebtoken.*;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;

public class JwtUtil {

    private static final String JWT_SECERT = "R9ctkmQzCRCQpaoatrs6Xbf9yIlY2nQl";

    public static String create(String userId, String jobNumber, String userName, long ttlMillis) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setIssuer("tclife-crm")
                .setIssuedAt(now)
                .claim("userId", userId)
                .claim("jobNumber", jobNumber)
                .claim("userName", userName)
                .signWith(signatureAlgorithm, secretKey);

        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date expDate = new Date(expMillis);
            builder.setExpiration(expDate);
        }

        return builder.compact();
    }

    public static JwtParseModel parse(String token) {
        Claims claims;
        try {
            SecretKey secretKey = generalKey();
            claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();

            return JwtParseModel.builder().success(true).claims(claims).build();
        } catch (ExpiredJwtException e) {
            return JwtParseModel.builder().success(false).msg("token已过期，请重新登录").build();
        } catch (Exception e) {
            return JwtParseModel.builder().success(false).msg("token解析失败，请重新登录").build();
        }
    }

    private static SecretKey generalKey() {
        byte[] encodedKey = Base64.decode(JWT_SECERT);
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }
}
